//
//  KAOTPVC.swift
//  kano
//
//  Created by Sophia on 2024/8/20.
//


import UIKit
import SnapKit
import RxSwift
import RxCocoa

class KAOTPVC: KABaseVC {
    var pwd: String = ""
    //校验手机号接口返回的token
    var mobileCodeToken: String = ""
    //区分老用户还是注册新用户
    var operationType: KAOperation = .Register
    //短信验证码发送返回codeToken，校验短信验证码接口用
    private var msgCodeToken: String = ""
    
    private let disposeBag = DisposeBag()
    private let titleLabel: UILabel = {
        let titleLabel = UILabel()
        titleLabel.textAlignment = .center
        titleLabel.font = UIFont.systemFont(ofSize: kscale(24), weight: .bold)
        titleLabel.textColor = .black
        titleLabel.text = "Enter OTP"
        titleLabel.x = kscale(20)
        titleLabel.y = kscale(40) + UIDevice.ka_fullNavHeight
        titleLabel.width = var_screenWidth-kscale(40)
        titleLabel.height = kscale(32)
        return titleLabel
    }()
    private let subTitleLabel: UILabel = {
        let subTitleLabel = UILabel()
        subTitleLabel.textAlignment = .center
        subTitleLabel.font = UIFont.systemFont(ofSize: kscale(13), weight: .regular)
        subTitleLabel.textColor = .color8A8891
        subTitleLabel.x = kscale(20)
        subTitleLabel.y = kscale(70) + UIDevice.ka_fullNavHeight
        subTitleLabel.width = var_screenWidth-kscale(40)
        subTitleLabel.height = kscale(32)
//        let holderText = "Please use +"
        let phoneNumber = KAUserManager.shared.user.mobile.maskedNumber
        let phoneStr = "+234 \(phoneNumber)"
        let allText = "Please use " + phoneStr + " to get the code"
        let attributedString = NSMutableAttributedString(string: allText)
        let holderTextRange = allText.nsRange(of: phoneStr)
        attributedString.addAttributes([
            .font: UIFont.systemFont(ofSize: kscale(11)),
            .foregroundColor: UIColor.themeColor
        ], range: holderTextRange)
        subTitleLabel.attributedText = attributedString
        return subTitleLabel
    }()
    private lazy var msgView: KAAuthView = {
        msgView = KAAuthView(count: 6, margin: kscale(12.5), borderColor: .color7E7EEC, backgroundColor: .color7E7EEC, handler: { code in
            if code.count == 6 {
                if self.operationType == .Register {
                    self.ka_verifyCode()
                } else if self.operationType == .OldPhoneLogin {
                    self.loginRequest()
                }
            }
        })
        return msgView
    }()
    private lazy var msgCodeBtn: UIButton = {
        let msgCodeBtn = UIButton()
        msgCodeBtn.backgroundColor = .colorf2f2f5
        msgCodeBtn.setTitle("Get Verification Code", for: .normal)
        msgCodeBtn.setTitleColor(.themeColor, for: .normal)
        msgCodeBtn.titleLabel?.font = UIFont.systemFont(ofSize: kscale(13), weight: .regular)
        msgCodeBtn.addTarget(self, action: #selector(msgCodeBtnClick), for: .touchUpInside)
        return msgCodeBtn
    }()
    @objc func msgCodeBtnClick() {
        ka_sendCode(withType: "0")
    }
    
    private let voiceCodeBtn: UIButton = {
        let voiceCodeBtn = UIButton()
        voiceCodeBtn.backgroundColor = .colorf2f2f5
        voiceCodeBtn.setTitle("Voice code", for: .normal)
        voiceCodeBtn.setTitleColor(.themeColor, for: .normal)
        voiceCodeBtn.titleLabel?.font = UIFont.systemFont(ofSize: kscale(13), weight: .regular)
//        voiceCodeBtn.addTarget(KAOTPVC.self, action: #selector(msgCodeBtnClick), for: .touchUpInside)
        return voiceCodeBtn
    }()
    
    
    lazy var var_pictureView: KAPictureVerifyView = {
        let var_pictureView = KAPictureVerifyView { [self] code, captcheId in
            captchaId = captcheId
            captchaCode = code
            ka_sendCode(withType: "0")
        }
        return var_pictureView
    }()
    //倒计时任务
    private var count: Int = 60
    private var task: String?
    //用于区分图片验证码和语音验证码
    private var currentCodeType: String?
    //图片验证码
    private var captchaCode: String = ""
    //图片验证码ID
    private var captchaId: String = ""
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setUI()
        setConstraints()
        ka_sendCode(withType: "0")
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        guard task != nil else { return }
        KATimer.cancelTask(task!)
    }
    
    private func setUI() {
        view.backgroundColor = .colorf2f2f5
        ka_showCustomerNavBar(type: .normal)
        var_navBar.updateUI(alpha: 0)
        
        view.addSubview(titleLabel)
        view.addSubview(subTitleLabel)
        view.addSubview(msgView)
        view.addSubview(msgCodeBtn)
//        view.addSubview(voiceCodeBtn)
        view.becomeFirstResponder()
    }
    
    private func setConstraints() {
  
        msgView.snp.makeConstraints { make in
            make.top.equalTo(subTitleLabel.snp.bottom).offset(kscale(41))
            make.left.equalTo(kscale(24))
            make.right.equalTo(kscale(-24))
            let width = (var_screenWidth - kscale(48) - kscale(60)) / 6
            make.height.equalTo(width)
        }
        
        msgCodeBtn.snp.makeConstraints { make in
            make.top.equalTo(msgView.snp.bottom).offset(kscale(10))
            make.centerX.equalTo(view)
        }
//        voiceCodeBtn.snp.makeConstraints { make in
//            make.top.equalTo(msgView.snp.bottom).offset(kscale(10))
//            make.centerX.equalTo(view)
//        }
    }
    
    private func ka_sendCode(withType codeType: String) {
        //注册发送验证码
        KAAFTool.logEvent(event: "SKP_sendverification_code")
        
        currentCodeType = codeType
        NetService.ka_sentCode(withType: codeType, codeToken: mobileCodeToken, operationType: operationType, captchaCode: captchaCode ?? "") { [self] isSuccess, message, response in
            self.captchaId = ""
            self.captchaCode = ""
            if isSuccess {
                self.view.makeToast("The verification code is sent successfully.")
                if response?.content != nil {
                    self.msgCodeToken = (response?.content!.codeToken)!
                }
                startTimer()
                self.var_pictureView.dismiss()
            } else {
                guard let status = response?.status else { return }
                if status == 1015 || status == 1016 || status == 1617 || status == 1618 || status == 1619 || status == 1014 || status == 1010 || status == 1017 || status == 7006 || status == 7007 || status == 7008  {
                    self.var_pictureView.show()
                    self.var_pictureView.makeToast(message)
                    return
                }
                self.view.makeToast(message)
                self.var_pictureView.dismiss()
            }
        }
    }
    
    private func ka_verifyCode() {
        let mobile = KAUserManager.shared.user.mobile
        let paramDic: [String: Any] = [
            "mobile": mobile,
            "verifyCode": msgView.code,
            "verifyToken": msgCodeToken,
            "codeToken": mobileCodeToken,
            "operationType": operationType.rawValue,
            "zuid": UIDevice.ka_UUID,
            "needSaveVerifyFlag": 1,
            "captchaId": "",
            "captchaCode": "",
            "needCheckImgCode": false,
        ]
        view.showLoading()
        loginProvider.request(.checkSmsCode(paramDic)) { [self] result in
            view.hideLoading()
            switch result {
            case .success(let response):
                if response.statusCode == 200 {
                    NetResponse<KAContent>.handleResponseData(response.data) { isSuccess, message, response in
                        if isSuccess {
                            guard let content = response?.content else {
                                view.makeToast("Verification failure"); return
                            }
                            if content.status == 1 {
                                //accountkit注册成功跳转设置密码
                                KAAFTool.logEvent(event: "SKP_Jumptoset_password")

                                let vc = KAPwdSetVC()
                                vc.msgCodeToken = msgCodeToken
                                vc.msgCode = msgView.code
                                navigationController?.pushViewController(vc, animated: true)
                                return
                            }
                            view.makeToast("Verification failure")
                        } else {
                            self.view.makeToast(message)
                        }
                    }
                }else {
                    self.view.makeToast(badNetWorking)
                }
            case .failure(let error):
                print(error.localizedDescription)
            }
        }
    }
    
    private func loginRequest() {
        NetService.ka_loginWith(mobile: KAUserManager.shared.user.mobile, password: pwd, codeToken: mobileCodeToken, operationType: operationType, verifyCode: msgView.code, verifyToken: msgCodeToken, captchaCode: "", captchaId: "", secondLogin: 0) {[self] isSuccess, message, response in
            if (!isSuccess) {
                view.makeToast(message)
                guard let status = response?.status else { return }
                if status == 1015 || status == 1016 || status == 1617 || status == 1618 || status == 1619 || status == 1014 || status == 1010 || status == 1017 || status == 7006 || status == 7007 || status == 7008  {
                    self.var_pictureView.show()
                    self.var_pictureView.makeToast(message)
                    return
                }
                self.view.makeToast(message)
                self.var_pictureView.dismiss()
            }
        }
    }
    
    private func startTimer() {
        count = 60
        task = KATimer.execTask(self, selector: #selector(countdown), start: 0.0, interval: 1.0, repeats: true, async: false)
    }
    
    @objc private func countdown() {
        let button: UIButton = (currentCodeType == "0") ? msgCodeBtn : voiceCodeBtn
        if count > 0 {
            count -= 1
            button.isUserInteractionEnabled = false
            button.setTitleColor(.color8A8891, for: .normal)
            let string = "(" + "\(count)" + "s)"
            button.setTitle(string, for: .normal)
        } else {
            KATimer.cancelTask(task!)
            button.setTitleColor(.themeColor, for: .normal)
            button.isUserInteractionEnabled = true
            if currentCodeType == "0" {
                voiceCodeBtn.isHidden = false
                button.setTitle("Resend", for: .normal)
            } else {
                button.setTitle("Voice code", for: .normal)
            }
        }
    }
}
